from sqlalchemy import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

import urldb.model
from   urldb.model.url import  *

class CmdLine(object):
    ''' 
    '''
    def __init__(self, c):
        self.control = c

    def print_tables(self):
        ses = self.control.get_session();
        u = ses.query(Url)[0]
        print 'URL:', u.url, u.created
        for r in u.params:
            print ' ID:', r.id, ' name:', r.name, ' val:', r.value


"""
 MAIN 
"""

from optparse import OptionParser
from urldb.control.populate  import Populate
from urldb.control.logparser import LogParser
from urldb.view.cmdline import CmdLine

def get_parser():
    parser = OptionParser()
    parser.set_defaults(
        create=False,
        database='sqlite:///url.db',
        format='extended',
        ignore=['_dc', 'appID', '0.0,0.0', 'Current Location'],
        log='/var/log/http/access.log',
        name=None,
        query=None,
        schema=None,
    )
    parser.add_option(
        "-c", "--create", action="store_true", dest="create",
        help="Create database tables"
    )
    parser.add_option(
        "-d", "--database", dest="database",
        help="Database connection string for engine (or just plain name, interpreted as name of sqlite db)"
    )
    parser.add_option(
        "-f", "--format", dest="format",
        help="Apache Log format"
    )
    parser.add_option(
        "-l", "--log", dest="log",
        help="Log file"
    )
    parser.add_option(
        "-n", "--name", dest="name",
        help="Default domain name, for urls without a domain name (eg: from apache)"
    )
    parser.add_option(
        "-q", "--query", dest="query",
        help="A simple case-sensitive string matcher, where only URLs that contain a -q <string> someplace in the url are stored"
    )
    parser.add_option(
        "-s", "--schema", dest="schema",
        help="Optional database schema name"
    )
    return parser

def init_parser():
    parser = get_parser()
    (options, args) = parser.parse_args()
    return options

def main():
    options = init_parser()
    l = LogParser(options)

def Xmain():
    options = init_parser()
    p = Populate(options)
    c = CmdLine(p)
    url = "http://a.com/y/z?x=k z d&m=n&from=7646000,682000&to=-122.5, 45.5"
    p.new_url(url)
    c.print_tables()


if __name__ == '__main__':
    main()
